import { login, logout, getUserInfo } from "@/api/user";
import { setLocal, getLocal, removeLocal } from "@/assets/js/funcs";
import { ElMessage } from "element-plus";

const state = {
    userInfo: getLocal("gdepUserInfo") || {},
    token: getLocal("gdepUserInfo")?.token || "",
    roles: [],
};

const getters = {
    isLogin: (state) => Object.keys(state.userInfo).length > 0 && state.token,
    username: (state) => state.userInfo?.user_name || state.userInfo?.account || "",
    userAvatar: (state) => state.userInfo?.avatar || "",
    userId: (state) => state.userInfo?.id || "",
};

const mutations = {
    SET_USER_INFO(state, userInfo) {
        state.userInfo = userInfo;
        state.token = userInfo?.token || "";
        setLocal("gdepUserInfo", userInfo);
    },
    SET_ROLES(state, roles) {
        state.roles = roles;
    },
    CLEAR_USER(state) {
        state.userInfo = {};
        state.token = "";
        state.roles = [];
        removeLocal("gdepUserInfo");
    },
};

const actions = {
    // 用户登录
    async login({ commit }, userInfo) {
        try {
            const { username, password } = userInfo;
            const response = await login({ username: username.trim(), password });
            if (response.code === 200 || response.code === 0) {
                commit("SET_USER_INFO", response.data);
                ElMessage({
                    type: "success",
                    message: "登录成功",
                });
                return Promise.resolve(response.data);
            } else {
                return Promise.reject(response);
            }
        } catch (error) {
            return Promise.reject(error);
        }
    },

    // 获取用户信息
    async getUserInfo({ commit, state }) {
        try {
            const response = await getUserInfo();
            if (response.code === 200 || response.code === 0) {
                const { data } = response;
                if (!data) {
                    return Promise.reject(new Error("验证失败，请重新登录"));
                }

                commit("SET_USER_INFO", { ...state.userInfo, ...data });
                commit("SET_ROLES", data.roles || []);
                return Promise.resolve(data);
            } else {
                return Promise.reject(response);
            }
        } catch (error) {
            return Promise.reject(error);
        }
    },

    // 用户退出登录
    async logout({ commit }) {
        try {
            await logout();
            commit("CLEAR_USER");
            return Promise.resolve();
        } catch (error) {
            return Promise.reject(error);
        }
    },

    // 重置令牌
    resetToken({ commit }) {
        commit("CLEAR_USER");
        return Promise.resolve();
    },
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
};
